#include "CoverUpload.as"
#include "CoverEdit.as"

var textUtil:MovieClip;
var dynamicPortlet:Object;

var finishedStatus:Boolean;
var bookId:String;

var booksResult:Object;
// var selectedBookId:String;

function init()
{
	Packages.model.Context.activeContent=this;

	// UI.init
	var basic=Packages.system.mlf.GateKeeper.scanElement(this._name, "basic");
	Packages.system.display.JAccordion.initialize(basic);

	// Render.init
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "bookCreationTitle"));
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "bookPageTitle"));
	Packages.system.display.SceneTransition.rollOut();

	// Event.init
	var evtTargetArr:Array=new Array();
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "coverBrowseSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "coverEditSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "infoCommitSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "infoResetSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "editApplySpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "editBackSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "BookList_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "back_print"));
	Packages.system.events.StateFulButtonEvent.initialize(evtTargetArr);

	invokeInitComplete();
}

function dispose()
{
	Packages.system.mlf.GateKeeper.removeListener("onReleaseButtonEvent", this);
	Packages.system.mlf.GateKeeper.removeListener("onTxtFocusOutEvent", this);
	delete dynamicPortlet;
	disposeCoverUpload();
	delete booksResult;
}

function invokeInitComplete()
{
	Packages.system.mlf.GateKeeper.addListener("onReleaseButtonEvent", this);
	Packages.system.mlf.GateKeeper.addListener("onTxtFocusOutEvent", this);

	textUtil=Packages.system.utils.TextUtil;

	dynamicPortlet=new Object();
	dynamicPortlet.bookInfo="bookInfoProperties";
	dynamicPortlet.relatedInfo="defaultInfoPortlet";

	// CoverEdit
	initializeCoverSize();

	// select the finishedStatusValue as default
	var finishedSpot=Packages.system.mlf.GateKeeper.scanElement(this._name, "finishedSpot");
	var param=mlf.mcmanager.PathResolver.drawPath(finishedSpot);
	Packages.system.events.StateFulButtonEvent.invokeReleaseEvent(param, data, this._name);
	finishedStatus=true;
	// mask the editStage
	var editStage=Packages.system.mlf.GateKeeper.scanElement(this._name, "editStage");
	var editStage_mask=Packages.system.mlf.GateKeeper.scanElement(this._name, "editStage_mask");
	editStage.setMask(editStage_mask);

	// initialize the cover upload
	initCoverUpload();
}

function coverBrowse() 
{
	openFileDialog();
}

function coverEdit()
{
	if (dynamicPortlet.bookInfo=="bookStageProperties")
	{
		Packages.modula.MessageCenter.send("IN_THE_EDIT_STAGE", 1, 0);
		return;
	}
	else
	{
		Packages.system.mlf.GateKeeper.updatePortletView(this._name, dynamicPortlet.bookInfo, "bookStageProperties");
		dynamicPortlet.bookInfo="bookStageProperties";
		initializeEditStage();
	}
}

function selectFinishStatus(finished:Boolean)
{
	finishedStatus=finished;
}

function infoCommit() 
{
	var obj:Object=new Object();
	obj.memberId=Packages.model.UserProfile.data.memberId;
	obj.bookName=textUtil.getValue("bookNameValue", this._name);
	obj.author=textUtil.getValue("authorNameValue", this._name);
	
	var data:Object=new Object();
	data.invokeCall="doInfoCommit";

	Packages.modula.RequestCommand.request("REMOTING", "bookCreate", obj, null, null, this, data);
}

function doInfoCommit(returnObj:String)
{
	bookId=returnObj;
	if (bookId==null)
	{
		Packages.modula.MessageCenter.send("BOOK_CREATION_FAIL", 1, 0);
		return;
	}

	var coverUuid=getUuid2Commit();
	if (coverUuid!=null)
	{
		var obj:Object=new Object();
		obj.bookId=bookId;
		obj.memberId=Packages.model.UserProfile.data.memberId;
		obj.image=getResourceDownloadUrl()+"?uuid="+coverUuid+"&type=3&"+"subtype="+subtype;
	
		Packages.modula.RequestCommand.request("REMOTING", "bookCoverVersionUpload", obj, null, null, this, null);
	}

	var obj:Object=new Object();
	obj.bookId=bookId;
	obj.memberId=Packages.model.UserProfile.data.memberId;
	obj.name=textUtil.getValue("bookNameValue", this._name);
	obj.author=textUtil.getValue("authorNameValue", this._name);
	obj.authorIntro=textUtil.getValue("authorPageValue", this._name);
	obj.subTitle=textUtil.getValue("bookTitleValue", this._name);
	obj.abstract=textUtil.getValue("descriptionValue", this._name);
	obj.publishPress=textUtil.getValue("publishNameValue", this._name);
	obj.publishYear=textUtil.getValue("publishDateValue", this._name);
	obj.chapterCount=textUtil.getValue("chapterNumValue", this._name);
	obj.wordCount=textUtil.getValue("wordNumValue", this._name);
	obj.completeStatus=finishedStatus?"1":"2";
	obj.website=textUtil.getValue("publishWebsiteValue", this._name);
	obj.url=textUtil.getValue("publishUrlValue", this._name);

	Packages.modula.RequestCommand.request("REMOTING", "bookInfoVersionCreate", obj, null, null, this, null);
}

function infoReset() 
{
	// select the finishedStatusValue as default
	var finishedSpot=Packages.system.mlf.GateKeeper.scanElement(this._name, "finishedSpot");
	var param=mlf.mcmanager.PathResolver.drawPath(finishedSpot);
	Packages.system.events.StateFulButtonEvent.invokeReleaseEvent(param, data, this._name);
	finishedStatus=true;

	textUtil.setDefaultValue("bookNameValue", this._name);
	textUtil.setDefaultValue("bookTitleValue", this._name);
	textUtil.setDefaultValue("authorNameValue", this._name);
	textUtil.setDefaultValue("authorPageValue", this._name);
	textUtil.setDefaultValue("publishNameValue", this._name);
	textUtil.setDefaultValue("publishDateValue", this._name);
	textUtil.setDefaultValue("publishWebsiteValue", this._name);
	textUtil.setDefaultValue("publishUrlValue", this._name);
	textUtil.setDefaultValue("chapterNumValue", this._name);
	textUtil.setDefaultValue("wordNumValue", this._name);
	textUtil.setDefaultValue("descriptionValue", this._name);
}

function editApply() 
{
	filterCoverByParams();	
}

function editBack() 
{
	if (dynamicPortlet.bookInfo=="bookInfoProperties")
	{
		return;
	}
	else
	{
		Packages.system.mlf.GateKeeper.updatePortletView(this._name, dynamicPortlet.bookInfo, "bookInfoProperties");
		dynamicPortlet.bookInfo="bookInfoProperties";
		disposeEditStage();
	}
}

function back2bookinfo()
{
	// record returnCode
	var returnObj_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "returnObj");
	var filteredUuid=returnObj_tf.text;
	setUuid2Commit(filteredUuid);

	Packages.system.mlf.GateKeeper.updateDynamicPortletView(this._name, "commonRemotingResult", "bookInfoProperties");
	dynamicPortlet.bookInfo="bookInfoProperties";
	// loadCover2Clip
	loadCover2Clip("clipCover", filteredUuid);
}
/*
function popupSelectedBookDetail()
{
	/*var bookItem;
	for (var i=0; i<booksResult.books.length; i++)
	{
		bookItem=booksResult.books[i];
		if (bookItem.bookId==selectedBookId)
		{
			Packages.system.display.Popup.createPopupByVO(Packages.model.vo.BookView, "popup", bookItem, null);
			break;
		}
	}*?
	Packages.system.mlf.GateKeeper.loadML2byPath("app/popup/BookDetail.xml");
}

function onBookDetailInit(param, data, slot)
{
	// Render.init
	Packages.system.render.Transition.irisType1(Packages.system.mlf.GateKeeper.scanElement(slot, "basic"));
	// Event.init
	var evtTargetArr:Array=new Array();
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(slot, "linkSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(slot, "closeSpot"));
	Packages.system.events.StateFulButtonEvent.initialize(evtTargetArr);
	// prefetch bookItem
	var bookItem;
	for (var i=0; i<booksResult.books.length; i++)
	{
		bookItem=booksResult.books[i];
		if (bookItem.bookId==selectedBookId)
		{
			break;
		}
	}
	// cover image
	var clipCover=Packages.system.mlf.GateKeeper.scanElement(slot, "clipCover");
	var mclListener=new Object();
	mclListener.owner=this;
	mclListener.onLoadInit=function(target_mc:MovieClip)
	{
		this.owner.resize(target_mc);
	}
	mlf.mcmanager.dynamicloading.LoadApp.loadAppLoader(bookItem.image, clipCover, "cover", mclListener);
	// data info
	var args:Array=new Array();
	args.push(bookItem);
	var vo:MovieClip=Packages.model.vo.BookView;
	var voData=vo["popup"].apply(vo, args);
	Packages.system.mlf.GateKeeper.setValue(voData.content, slot);
}

function resize(target:MovieClip)
{
	zoom=Packages.system.utils.ImageUtil.minSize(target, 120, 150);
	target._xscale=zoom;
	target._yscale=zoom;
	// centralize the target
	var offsetX:Number=(target._width-120)/2;
	target._x=-offsetX;
	var offsetY:Number=(target._height-150)/2;
	target._y=-offsetY;
}
*/
function onReleaseButtonEvent(evt:Object)
{
	// Packages.log(evt.type+": "+evt.param);
	if (evt.param=="coverBrowseSpot")
	{
		coverBrowse();
	}
	else if (evt.param=="coverEditSpot")
	{
		coverEdit();
	}
	else if (evt.param=="finishedSpot")
	{
		selectFinishStatus(true);
	}
	else if (evt.param=="unfinishedSpot")
	{
		selectFinishStatus(false);
	}
	else if (evt.param=="infoCommitSpot")
	{
		infoCommit();
	}
	else if (evt.param=="infoResetSpot")
	{
		infoReset();
	}
	else if (evt.param=="editApplySpot")
	{
		editApply();
	}
	else if (evt.param=="editBackSpot")
	{
		editBack();
	}
	else if (evt.param=="resultReturnSpot")
	{
		var path=Packages.system.mlf.GateKeeper.scanElement(this._name, "resultReturnPath");
		
		this[path.text].apply(this, null);
	}
	else if (evt.param.indexOf("bookItem")>-1)
	{
		var selectedBookId=evt.param.substr(9);
		Packages.system.utils.ComponentsUtil.popupSelectedDataDetail(booksResult, selectedBookId, "BookDetail", "content/bookPage/BookSpecial");
	}
	/*else if (evt.param=="closeSpot")
	{
		// Packages.system.mlf.GateKeeper.unloadML2bySlot("BookDetail");
		Packages.system.mlf.GateKeeper.removePopup("BookDetail");
	}
	else if (evt.param=="linkSpot")
	{
		Packages.system.mlf.GateKeeper.removePopup("BookDetail");
		Packages.components.SceneAgent.loadScene("content/bookPage/BookSpecial?id="+selectedBookId);
	}*/
}

function onTxtFocusOutEvent(evt:Object)
{
	Packages.log(evt.type+": "+evt.param);

	// sample code:
	var elementStr=mlf.mcmanager.PathResolver.drawPath(evt.param);
	var dynamicContainer=Packages.system.mlf.GateKeeper.scanElement(this._name, "relatedInfoContainer");

	if (elementStr.indexOf("bookNameValue")>-1)
	{
		Packages.system.display.Progress.createInstance(Packages.system.mlf.GateKeeper.scanElement(this._name, "relatedInfoContainer"));

		var bookName=textUtil.getValue("bookNameValue", this._name);
		if (bookName=="") return;

		Packages.modula.RequestCommand.request("HTTP", "restlet/books/searchByName/"+escape(bookName)+"?startIndex=-1&count=-1", null, Packages.model.vo.BookListView, "minimize", this, {container:"relatedInfoContainer", dynamicPortlet:dynamicPortlet.relatedInfo, portletName:"bookNameRelated", saved:"booksResult"});

		dynamicPortlet.relatedInfo="bookNameRelated";
	}
	else if (elementStr.indexOf("authorNameValue")>-1)
	{
		Packages.system.display.Progress.createInstance(Packages.system.mlf.GateKeeper.scanElement(this._name, "relatedInfoContainer"));

		var authorName=textUtil.getValue("authorNameValue", this._name);
		if (authorName=="") return;

		Packages.modula.RequestCommand.request("HTTP", "restlet/books/searchByAuthor/"+escape(authorName)+"?startIndex=-1&count=-1", null, Packages.model.vo.BookListView, "minimize", this, {container:"relatedInfoContainer", dynamicPortlet:dynamicPortlet.relatedInfo, portletName:"authorNameRelated", saved:"booksResult"});

		dynamicPortlet.relatedInfo="authorNameRelated";
	}
}

function handleResponseResult(rsp:Object)
{
	Packages.log("rsp.service.method: "+rsp.service.method, "debug");
	var rst=rsp.service.result;
	for (var a in rst)
	{
		Packages.log(a+": "+rst[a], "debug");
	}

	if (rsp.vo.instance.type=="Template" && rsp.service.type=="HTTP")
	{
		var dynamicPortletIns=Packages.system.mlf.GateKeeper.scanElement(this._name, rsp.component.data.dynamicPortlet);
		Packages.system.mlf.GateKeeper.updateDynamicPortlet(dynamicPortletIns, null, rsp.vo.instance.content);
	}

	if (rsp.service.method=="bookInfoVersionCreate")
	{
		if (rsp.service.result.returnCode==0)
		{
			Packages.modula.MessageCenter.send("BOOK_CREATION_SUCCESS", 1, 0);
			Packages.components.SceneAgent.loadScene("content/bookPage/BookSpecial?id="+bookId);
		}
		else Packages.modula.MessageCenter.send("BOOK_CREATION_FAIL", 1, 0);
	}
	else if (rsp.service.method=="bookCoverVersionUpload")
	{
		if (rsp.service.result.returnCode==0)
		{
			Packages.modula.MessageCenter.send("BOOK_COVER_UPLOAD_SUCCESS", 1, 0);
		}
		else Packages.modula.MessageCenter.send("BOOK_COVER_UPLOAD_FAIL", 1, 0);
	}
	else if (rsp.service.method=="bookCoverFilter")
	{
		Packages.system.mlf.GateKeeper.updateDynamicPortletView(this._name, dynamicPortlet.bookInfo, "commonRemotingResult", rsp.vo.instance.content);
	}

	if (rsp.component.data.saved!=null)
	{
		this[rsp.component.data.saved]=rsp.service.result;
	}

	if (rsp.component.data.invokeCall!=null)
	{
		if (rsp.component.data.invokeArgs==null)
		{
			rsp.component.data.invokeArgs=new Array();
		}
		rsp.component.data.invokeArgs.push(rsp.service.result.returnObj.toString());
		
		this[rsp.component.data.invokeCall].apply(this, rsp.component.data.invokeArgs);
	}
	Packages.system.display.Progress.removeInstance(Packages.system.mlf.GateKeeper.scanElement(this._name, rsp.component.data.container));
}